<template>
  <div class="management">
    <div class="mains_contain">
      <el-form :inline="true" :model="searchForm" size="small" label-width="80px">
        <el-form-item>
          <el-button type="primary" @click="handlerAdd" icon="el-icon-plus" size="mini" v-has="['user:add']">新增</el-button>
        </el-form-item>
        <el-form-item label="账号">
          <el-input v-model="searchForm.username" clearable placeholder="请输入账号" />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="searchForm.realName" clearable placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="searchForm.mobile" clearable placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" clearable placeholder="请选择状态">
            <el-option label="正常" :value="1"></el-option>
            <el-option label="冻结" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search" icon="el-icon-search" size="mini">查询</el-button>
        </el-form-item>
      </el-form>
      <div class="contant">
        <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange" fit :max-height="maxHeight" border stripe size="mini" highlight-current-row
          :header-cell-style="{ background: '#e5e5e5', color: '#000' }">
          <el-table-column prop="username" label="账号" sortable />
          <el-table-column prop="realName" label="姓名" sortable />
          <el-table-column prop="tenantTxt" label="租户" sortable />

          <el-table-column prop="mobile" label="手机号" sortable />
          <el-table-column prop="status" label="状态" sortable>
            <template slot-scope="scope">
              <!-- <el-tag
                effect="dark"
                size="mini"
                v-if="scope.row.status == 1"
                type="success"
                >正常</el-tag
              >
              <el-tag
                effect="dark"
                size="mini"
                v-if="scope.row.status == 0"
                type="danger"
                >锁定</el-tag
              > -->
              <span style="color: #f56c6c" v-if="scope.row.status == '0'">锁定</span>
              <span style="color: #67c23a" v-if="scope.row.status == '1'">正常</span>
            </template>
          </el-table-column>
          <!-- <el-table-column prop="loginTimes" label="登录次数" sortable />
          <el-table-column prop="loginTime" label="登录时间" sortable>
            <template slot-scope="scope">
              {{ scope.row.loginTime }}
            </template>
          </el-table-column> -->
          <el-table-column prop="createTime" label="创建时间" sortable>
            <template slot-scope="scope">
              {{ scope.row.createTime }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="250" align="center">
            <template slot-scope="{ row, $index }">
              <el-button type="text" size="mini" style="margin-right: 10px" v-has="['user:edit']" @click="handlerUpdate(row)" icon="el-icon-edit">编辑</el-button>
              <!-- <el-button type="danger" size="mini" icon="el-icon-delete" @click="handleDelete(row)">删除</el-button> -->
              <el-dropdown @command="handleCommand">
                <span class="el-dropdown-link">
                  <el-button type="text" size="small">更多</el-button><i class="el-icon-arrow-down el-icon--right"></i>
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item :command="{ type: 'a', row: row }" v-has="['user:resetPassword']">
                    <span>重置密码</span>
                  </el-dropdown-item>
                  <el-dropdown-item :command="{ type: 'b', row: row }" v-has="['user:delete']">
                    <span>删除</span>
                  </el-dropdown-item>
                  <!-- <el-dropdown-item
                    :command="{ type: 'c', row: row }"
                    v-has="['user:freeze']"
                  >
                    <span>冻结</span>
                  </el-dropdown-item> -->
                  <el-dropdown-item :command="{ type: 'd', row: row }" v-has="['user:editPassword']">
                    <span>密码修改</span>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
        <div style="text-align: right">
          <pagination v-show="pagination.total > 0" :limit.sync="pagination.pageSize" :page.sync="pagination.page" :total="pagination.total" @pagination="getPageList" />
        </div>
      </div>
    </div>
    <el-dialog :title="title" :visible.sync="dialogVisible" width="500px" @close="cancleAdd" :close-on-click-modal="false">
      <el-form ref="form" :model="form" label-width="100px" :inline="false" size="small" :rules="rules">
        <el-form-item label="租户" prop="relTenantIds">
          <el-select v-model="form.relTenantIds" style="width: 100%" placeholder="请选择" @change="change" multiple>
            <el-option :label="item.name" v-for="item in tenantList" :value="item.id" :key="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="账号" prop="username">
          <el-input v-model="form.username" clearable />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!form.id">
          <el-input v-model="form.password" clearable />
        </el-form-item>
        <el-form-item label="姓名" prop="realName">
          <el-input v-model="form.realName" clearable />
        </el-form-item>
        <el-form-item label="角色" prop="selectedRoles">
          <el-select v-model="form.selectedRoles" style="width: 100%" placeholder="请选择" :disabled="!(form.relTenantIds && form.relTenantIds.length > 0)">
            <el-option :label="item.name" v-for="item in roleList" :value="item.id" :key="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="form.mobile" clearable />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">冻结</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div style="text-align: right">
        <el-button type="primary" @click="handlerSave" size="small">保存</el-button>
        <el-button @click="cancleAdd" size="small">取消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="修改密码" :visible.sync="changePasswordVisible" width="500px" @close="cancle" :close-on-click-modal="false">
      <el-form ref="changePasswordForm" :model="changePasswordForm" label-width="100px" :inline="false" size="small" :rules="rules">
        <el-form-item label="旧密码" prop="oldPassword">
          <el-input v-model="changePasswordForm.oldPassword" clearable placeholder="登录密码" @input="changePwd" />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="changePasswordForm.newPassword" clearable placeholder="请输入新密码" @input="changePwd2" />
        </el-form-item>
      </el-form>
      <div style="text-align: right">
        <el-button type="primary" @click="changePasswordSave('changePasswordForm')" size="small">保存</el-button>
        <el-button @click="cancle" size="small">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as api from "@/api/sys/user";
import * as tenantApi from "@/api/sys/tenant";
import * as roleApi from "@/api/sys/role";
import { mapGetters } from "vuex";
import { passwords, cnPhone, account } from "@/utils/validate";

export default {
  comments: {},
  props: {},
  data() {
    const validateUsername = (rule, value, callback) => {
      if (value == "" || !value) {
        callback(new Error("请输入用户名"));
      } else {
        if (account(value)) {
          callback();
        } else {
          callback(new Error("用户名只能是字母或者数字"));
        }
      }
    };
    return {
      tenantList: [], //租户列表
      roleList: [],
      activeValue: 0,
      inactiveValue: 1,
      title: "",
      dialogVisible: false,
      searchForm: {},
      form: {
        relTenantIds: [],
        status: 1,
      },
      changePasswordVisible: false,
      changePasswordForm: {
        userId: null,
        oldPassword: null,
        newPassword: null,
      },
      multipleSelection: [],
      tableData: [],
      pagination: {
        total: 0,
        page: 1,
        pageSize: 10,
      },
      rules: {
        relTenantIds: [
          { required: true, message: "请选择租户", trigger: "blur" },
        ],
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { trigger: "blur", validator: validateUsername },
        ],
        mobile: [
          { required: true, validator: this.validateMobie, trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { validator: this.validatePass, trigger: "blur" },
        ],
        oldPassword: [
          { required: true, message: "请输入旧密码", trigger: "blur" },
        ],
        newPassword: [{ validator: this.validatePassOther, trigger: "blur" }],
        realName: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        selectedRoles: [
          { required: true, message: "请选择角色", trigger: "blur" },
        ],
        checkTenantIds: "",
      },
    };
  },
  computed: {
    maxHeight() {
      var curHeight =
        window.innerHeight ||
        document.documentElement.clientHeight ||
        document.body.clientHeight;
      return curHeight - 280;
    },
    ...mapGetters(["userInfo"]),
  },
  created() {
    this.getPageList();
    this.getTenantList();
    // this.getRoleList();
  },
  mounted() {
    let relTenantIds = this.userInfo.userInfo.relTenantIds;
    if (!relTenantIds) {
      this.rules = {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        mobile: [
          { required: true, validator: this.validateMobie, trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { validator: this.validatePass, trigger: "blur" },
        ],
        oldPassword: [
          { required: true, message: "请输入旧密码", trigger: "blur" },
        ],
        newPassword: [
          {
            required: true,
            validator: this.validatePassOther,
            trigger: "blur",
          },
        ],
        realName: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        selectedRoles: [
          { required: true, message: "请选择角色", trigger: "blur" },
        ],
      };
    }
  },
  methods: {
    changePwd(val) {
      this.changePasswordForm.oldPassword = val.replace(/\s+/g, "")
    },
    changePwd2(val) {
      this.changePasswordForm.newPassword = val.replace(/\s+/g, "")
    },
    validatePass(rule, value, callback) {
      if (!passwords(value)) {
        callback(
          new Error("必须包含大小写字母、数字、特殊字符长度在8-16位之间!!")
        );
      } else {
        callback();
      }
    },
    validatePassOther(rule, value, callback) {
      if (!passwords(value)) {
        callback(
          new Error("必须包含大小写字母、数字、特殊字符长度在8-16位之间!!")
        );
      } else {
        callback();
      }
    },
    validateMobie(rule, value, callback) {
      if (value === "" || !value) {
        callback(new Error("请输入手机号"));
      } else if (!cnPhone(value)) {
        callback(new Error("请输入正确的手机号"));
      } else {
        callback();
      }
    },
    cancleAdd() {
      this.dialogVisible = false;
      this.$refs.form.resetFields();
      this.form = {}
    },
    cancle() {
      this.changePasswordVisible = false;
      this.$refs.changePasswordForm.resetFields();
      // this.changePasswordForm = {}

    },
    // 获取角色数据
    getRoleList() {
      roleApi.queryall({ tenantId: this.checkTenantIds }).then((res) => {
        if (res.code == "200") {
          this.roleList = res.data;
        }
      });
    },
    changePasswordSave(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log(this.changePasswordForm);
          api.changePassword(this.changePasswordForm).then((res) => {
            if (res.code == "200") {
              this.$message({
                type: "success",
                message: "密码修改成功!",
              });
              this.changePasswordVisible = false;
            }
          });
        } else {
          return false;
        }
      });
    },
    handleCommand(command) {
      console.log(command, "=======command");
      switch (command.type) {
        case "a":
          this.changePasswordForm.userId = command.row.id;
          this.$confirm("此操作将重置密码为123456, 是否继续?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }).then(() => {
            api.resetPassWord(command.row.id).then((res) => {
              this.$message({
                type: "success",
                message: "重置成功!",
              });
              this.changePasswordVisible = false;
            });
          });
          break;
        case "b":
          this.handleDelete(command.row);
          break;
        case "c":
          // this.onNetworkInfo(command.row)
          break;
        case "d":
          this.changePasswordForm.userId = command.row.id;
          this.changePasswordVisible = true;
          break;
      }
    },
    // 获取租户数据
    getTenantList() {
      tenantApi.queryIdNamePair().then((res) => {
        // console.log(res)
        this.tenantList = res.data;
      });
    },
    //删除
    handleDelete(row) {
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          api.deleteId(row.id).then((resp) => {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            if ((this.pagination.total - 1) % this.pagination.pageSize == 0) {
              if (this.pagination.page > 1) {
                this.pagination.page = this.pagination.page - 1;
              }
            }
            this.search();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 复选框事件
    handleSelectionChange(val) {
      // this.multipleSelection = val;
    },
    getPageList() {
      this.search();
    },
    search() {
      var params = {};
      Object.keys(this.searchForm).forEach((item) => {
        if (this.searchForm[item] != "" && this.searchForm[item]) {
          params[item] = this.searchForm[item];
        }
      });
      params.status = this.searchForm.status;
      const p = Object.assign({}, this.pagination, params);
      api.page(p).then((resp) => {
        this.tableData = resp.data.list;
        this.pagination = resp.data.pagination;
        this.pagination.page = resp.data.pagination.current;
      });
    },
    handlerAdd() {
      this.title = "新增";
      this.dialogVisible = true;
      this.form = {
        // relTenantIds: [],
        status: 1,
      };
    },
    change(value) {
      console.log(value);
      this.roleList = [];
      this.checkTenantIds = value.join(",");
      if (this.title == "修改") {
        this.form.selectedRoles = "";
      }
      this.getRoleList();
    },
    async handlerUpdate(row) {
      console.log(row);
      this.checkTenantIds = row.relTenantIds;
      this.getRoleList();
      this.title = "修改";
      this.form = Object.assign({}, row);
      if (this.form.relTenantIds && this.form.relTenantIds.indexOf(",") > -1) {
        this.form.relTenantIds = this.form.relTenantIds.split(",");
      } else if (
        this.form.relTenantIds &&
        this.form.relTenantIds.indexOf(",") < 0
      ) {
        if (typeof this.form.relTenantIds == "string") {
          this.form.relTenantIds = [this.form.relTenantIds];
        } else if (typeof this.form.relTenantIds == "object") {
          this.form.relTenantIds = this.form.relTenantIds;
        }
      } else {
        console.log(1111);
      }
      var queryUserRole = await api.queryUserRole({ userid: row.id });
      this.dialogVisible = true;
      if (queryUserRole.data) {
        this.form.selectedRoles = queryUserRole.data[0];
      } else {
        this.form.selectedRoles = [];
      }
    },
    handlerSave() {
      // console.log(this.form)
      this.$refs["form"].validate((valid) => {
        if (valid) {
          let relTenantId = this.userInfo.userInfo.relTenantIds;
          if (!relTenantId && !this.form.relTenantIds) {
            this.form.relTenantIds = null;
          }
          var p = Object.assign({}, this.form);

          if (p.relTenantIds) {
            p.relTenantIds = p.relTenantIds.join(",");
          }
          // if (p.selectedRoles) {
          //   p.selectedRoles = p.selectedRoles.join(",");
          // }
          if (this.form.id) {
            api.update(p).then((resp) => {
              console.log(resp);
              if (resp.code == 200) {
                this.$message({
                  type: "success",
                  message: "修改成功!",
                });
                this.getPageList();
                this.dialogVisible = false;
              }
            });
          } else {
            api.save(p).then((resp) => {
              if (resp.code == 200) {
                this.$message({
                  type: "success",
                  message: "新增成功!",
                });
                this.getPageList();
                this.dialogVisible = false;
              }
            });
          }
        }
      });
    },
  },
};
</script>

<style scoped lang="scss">
.management {
  padding: 20px;

  .curHeader {
    position: relative;
    height: 40px;
    .searcherBox {
      position: absolute;
      right: 0;
      top: 0;
    }
  }
}
</style>
